package com.mindbook.vip.gawxchatinfo.service.impl.user;

import com.mindbook.vip.gawxchatinfo.config.shiro.LoginTypeToken;
import com.mindbook.vip.gawxchatinfo.entity.user.UserFront;
import com.mindbook.vip.gawxchatinfo.exception.sql.SqlException;
import com.mindbook.vip.gawxchatinfo.mapper.user.UserFrontMapper;
import com.mindbook.vip.gawxchatinfo.service.user.UserFrontService;
import com.mindbook.vip.gawxchatinfo.utils.result.Result;
import com.mindbook.vip.gawxchatinfo.utils.result.ResultEnum;
import com.mindbook.vip.gawxchatinfo.utils.result.ResultUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author wxb
 * @Datatime 2022/4/6 13:17
 * @Descript
 */
@Service
public class UserFrontServiceImpl implements UserFrontService {

    @Autowired private UserFrontMapper userFrontMapper;

    @Override
    public UserFront selectByPhoneNumber(String phoneNumber) {
        UserFront userFront = userFrontMapper.selectByPhoneNumber(phoneNumber);
        return userFront;
    }

    /**
     * 因为phoneNumber
     * @param phoneNumber 手机号
     * @param openId 微信号的openId
     * @return
     */
    @Override
    public Result insert(String phoneNumber, String openId) {

        UserFront selectObj = userFrontMapper.selectByPhoneNumber(phoneNumber);
        if(selectObj==null){
            UserFront userFront = new UserFront();
            userFront.setPhonenumber(Long.parseLong(phoneNumber));
            userFront.setOpenid(openId);
            int insert = insert(userFront);
            if(insert!=1){
                //插入数据失败
                throw new SqlException(ResultEnum.SQL_HANDLER_NO_CHANGE.getCode(),ResultEnum.SQL_HANDLER_NO_CHANGE.getMsg());
            }
        }
        return frontLogin(phoneNumber, openId);
    }

    public int insert(UserFront userFront){
        return userFrontMapper.insert(userFront);
    }

    @Override
    public UserFront selectInfo() {
        return null;
    }

    /**
     * 用户进行登录
     * @param phoneNumber
     * @param openId
     * @return
     */
    private Result frontLogin(String phoneNumber,String openId){
        System.out.println("进入了微信登录校验中");
        Subject subject = SecurityUtils.getSubject();
        subject.isAuthenticated();

        LoginTypeToken token = new LoginTypeToken(phoneNumber,openId,"UserFrontRealm");
        subject.login(token);

        return ResultUtils.genSuccessResult(ResultEnum.SHIRO_LOGIN_SUCCESS);
    }
}
